package com.xian.im.modules.sensitive.handler;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.xian.im.modules.sensitive.load.SensitiveLoad;

import java.nio.charset.Charset;
import java.util.Collection;

/**
 * @program: xian-im-server
 * @description:
 * @author: liru.xian
 * @create: 2021-02-23 09:29
 **/
public class GuavaBloomHandler implements SensitiveBloom {

    private static BloomFilter<String> filter = BloomFilter.create(Funnels.stringFunnel(Charset.forName("utf-8")), 150000, 0.0001);

    /**
     * 初始化敏感词库
     *
     * @param \
     * @return
     */
    @Override
    public boolean loadSensitive() {
        SensitiveLoad instance = SensitiveLoad.getInstance();
        for (String s : instance.container()) {
          filter.put(s);
        }
        return Boolean.TRUE;
    }

    /**
     * 布隆类型
     */
    @Override
    public String getType() {
        return GUAVA_TYPE;
    }

    /**
     * 添加敏感词
     *
     * @param word
     * @return
     */
    @Override
    public Boolean add(String word) {
        return  filter.put(word);
    }

    /**
     * 添加敏感词
     *
     * @param words
     * @return
     */
    @Override
    public Boolean addAll(Collection<String> words) {
        for (String s : words) {
            filter.put(s);
        }
        return Boolean.TRUE;
    }

    /**
     * 判断是否是敏感词
     *
     * @param word
     * @return
     */
    @Override
    public Boolean includeByBloomFilter(String word) {
        return filter.mightContain(word);
    }

    /**
     * @return
     */
    @Override
    public Boolean reset() {
        return null;
    }
}
